using System;
using System.Windows;
using Microsoft.Xaml.Behaviors;

/*
 * 源码已托管：https://gitee.com/dlgcy/WPFTemplateLib
 */
namespace WPFTemplateLib.Behaviors
{
	/// <summary>
	/// 在行为中使用的 路由事件触发器（支持附加事件）
	/// 调整自：https://sergecalderara.wordpress.com/2012/08/23/how-to-attached-an-mvvm-eventtocommand-to-an-attached-event/
	/// </summary>
	/// <example>
	/// <code>
	/// &lt;b:Interaction.Triggers&gt;
	///     &lt;helpers:RoutedEventTrigger RoutedEvent="local:YourAttachedEventHelper.YourAttachedEvent"&gt;
	///         &lt;b:InvokeCommandAction Command="{Binding YourCmd}" EventArgsParameterPath="OriginalSource"/&gt;
	///     &lt;/helpers:RoutedEventTrigger&gt;
	/// &lt;/b:Interaction.Triggers&gt;
	/// </code>
	/// </example>
	public class RoutedEventTrigger : EventTriggerBase<DependencyObject>
	{
		/// <summary>
		/// 路由事件/附加事件
		/// </summary>
		public RoutedEvent RoutedEvent { get; set; }

		protected override void OnAttached()
		{
			FrameworkElement associatedElement = AssociatedObject as FrameworkElement;

			if(AssociatedObject is Behavior behavior)
			{
				associatedElement = ((IAttachedObject)behavior).AssociatedObject as FrameworkElement;
			}

			if(associatedElement == null)
			{
				throw new ArgumentException("Routed Event trigger can only be associated to framework elements");
			}

			if(RoutedEvent != null)
			{
				associatedElement.AddHandler(RoutedEvent, new RoutedEventHandler(OnRoutedEvent));
			}
		}

		void OnRoutedEvent(object sender, RoutedEventArgs args)
		{
			base.OnEvent(args);
		}

		protected override string GetEventName()
		{
			return RoutedEvent.Name;
		}
	}
}
